<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import uploadFile from '@/utils/uploadFile'

const router = useRouter()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const titleText = ref('')
const mainText = ref('')
const fileList = ref([])
const AddressText = ref('')
const thePower = ref(0)

// function submitNote() {
//   console.log(fileList.value[0].raw)
//     let formData = new FormData();
//     formData.append('title', titleText.value+"");
//     formData.append('context', mainText.value+"");
//     formData.append('power', thePower.value);
//     formData.append('address', AddressText.value+"");
//     // formData.append('files',fileList.value);

//     console.log(fileList)

//     fileList.value.forEach(file => {
//         console.log(file)
//         formData.append('files', file.raw);
//         //获取宽高
//         var reader = new FileReader();
//         reader.onload = function (event) {
//             var txt = event.target.result;
//             var img = document.createElement("img");
//             img.src = txt;
//             img.onload = function () {
//                 console.log(img.width);
//                 console.log(img.height);
//                 formData.append('width', img.width);
//                 formData.append('height', img.height);
//             };
//         };
//         reader.readAsDataURL(file.raw);
//     });

//     for (let pair of formData.entries()) {
//         console.log(pair[0] + ', ' + pair[1]);
//     }

//     try {
//         uploadFile.post('/user/submitNote',formData).then(res=>{
//           console.log(res)
//           if(res.code === 1){
//             ElNotification({
//               title: 'Success',
//               message: '发布成功',
//               type: 'success',
//             })
//             router.push("/creator")
//           }else{
//             ElNotification({
//               title: 'Error',
//               message: '网络错误,发布失败',
//               type: 'error',
//             })
//           }
//         })
//     } catch (error) {
//         console.error('提交失败', error);
//     }
// }

async function submitNote() {
  //提交表单
  try {
    let formData = new FormData()
    formData.append('title', titleText.value || '') // 添加标题，确保有值
    formData.append('context', mainText.value || '') // 添加内容，确保有值
    formData.append('power', thePower.value) // 添加权限信息，确保有值
    formData.append('address', AddressText.value || '') // 添加地址信息，确保有值

    // 获取文件列表
    const files = fileList.value

    // 遍历文件列表
    for (let i = 0; i < files.length; i++) {
      const file = files[i].raw
      formData.append('files', file) // 将文件加入表单数据

      // 使用FileReader读取文件信息
      const reader = new FileReader()
      reader.readAsDataURL(file) // 读取文件为Data URL

      // 等待文件加载完成
      await new Promise((resolve) => {
        reader.onload = function (event) {
          const img = new Image()
          img.src = event.target.result

          img.onload = function () {
            formData.append('width', img.width) // 添加图片宽度
            formData.append('height', img.height) // 添加图片高度
            resolve()
          }
        }
      })
    }

    // 打印表单数据（测试用）
    for (let pair of formData.entries()) {
      console.log(pair[0] + ', ' + pair[1])
    }

    // 发送表单数据到后端
    try {
      uploadFile.post('/user/submitNote', formData).then((res) => {
        console.log(res)
        if (res.code === 1) {
          ElNotification({
            title: 'Success',
            message: '发布成功',
            type: 'success'
          })
          router.push('/creator')
        } else {
          ElNotification({
            title: 'Error',
            message: '网络错误,发布失败',
            type: 'error'
          })
        }
      })
    } catch (error) {
      console.error('提交失败', error)
    }
  } catch (error) {
    console.error('提交失败', error)
    ElNotification({
      title: 'Error',
      message: '提交失败，请稍后再试',
      type: 'error'
    })
  }
}

function handleDownload(file) {
  var reader = new FileReader()
  reader.onload = function (event) {
    var txt = event.target.result
    var img = document.createElement('img')
    img.src = txt
    img.onload = function () {
      console.log(img.width)
      console.log(img.height)
    }
  }
  reader.readAsDataURL(file.raw)
}

function handleRemove(file) {
  console.log(fileList)
  const index = fileList.value.indexOf(file.uid)
  fileList.value.splice(index, 1)
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url || ''
  dialogVisible.value = true
}

// const handleDownload = (file) => {
//   console.log(file)
// }

function handleClear() {
  fileList.value.splice(0, fileList.value.length)
}

// onMounted(()=>{
//     const uploadedFile = JSON.parse(localStorage.getItem('uploadedFile'));
//     console.log('Uploaded file:', uploadedFile);
//     fileList.value.push(uploadedFile);
//     // if(fileList.value.length < 1){
//     //     router.push("/creator/upPT")
//     // }
// })
</script>

<template>
  <div class="main-box">
    <div class="box-left">
      <div class="left-title">
        <div
          style="
            height: 20px;
            width: 5px;
            border-radius: 5px;
            background-color: red;
            margin-right: 3px;
          "
        ></div>
        <a style="font-size: 18px"> 发布图文 </a>
      </div>
      <div class="edit-picture">
        <a style="font-size: 18px">
          图片编辑<span style="font-size: 14px; color: #adadad; padding-left: 10px"
            >({{ fileList.length }}/9)</span
          >
          <div
            style="color: rgb(243, 0, 0); float: right; font-size: 12px; cursor: pointer"
            @click="handleClear()"
          >
            清空并重新上传
          </div>
        </a>
        <div class="picture-adds">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            limit="9"
            v-model:file-list="fileList"
            multiple="true"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleDownload(file)"
                  >
                    <el-icon><Download /></el-icon>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>

          <el-dialog
            v-model="dialogVisible"
            style="max-width: 100%; background: none; box-shadow: none"
          >
            <img
              :src="dialogImageUrl"
              alt="Preview Image"
              style="max-width: 100%; max-height: 100%; height: auto"
            />
          </el-dialog>
        </div>
        <div style="color: red; font-size: 12px" v-if="fileList.length == 0">
          发布笔记至少需要一张图片
        </div>
      </div>
      <label>
        <input
          v-model="titleText"
          class="box-title"
          placeholder="填写标题, 可能会有更多赞哦 ~"
          maxlength="20"
        />
        <span>{{ titleText.length }}</span
        ><span style="color: #adadad">/20</span><br />
      </label>
      <textarea
        v-model="mainText"
        class="box-main"
        placeholder="填写更全面的描述信息, 让更多的人看到你吧!"
        maxlength="1000"
      />
      <span>{{ mainText.length }}</span
      ><span style="color: #adadad">/1000</span>
      <div class="tags">
        <div class="tag"># 话题</div>
        <div class="tag">@ 用户</div>
        <div class="tag">表情</div>
      </div>
      <div class="edit-submit">
        <span class="submit-title"> 发布设置 </span>
        <div class="address">
          <span class="address-title"> 添加地点 </span>
          <input class="address-input" placeholder="请选择地点" v-model="AddressText" />
        </div>
        <div class="public-or-private">
          <span class="title"> 权限设置 </span>
          <label>
            <input
              type="radio"
              name="visibility"
              class="public"
              checked
              value="0"
              v-model="thePower"
            />
            <span>
              <span> 公开 </span>
              <span style="color: #7a7a7a"> (所有人可见) </span>
            </span>
          </label>
          <label>
            <input type="radio" name="visibility" class="private" value="1" v-model="thePower" />
            <span>
              <span> 私密 </span>
              <span style="color: #7a7a7a"> (仅自己可见) </span>
            </span>
          </label>
        </div>
        <div class="submit-time">
          <span class="title"> 发布时间 </span>
          <label for="now">
            <input type="radio" name="submitTime" class="now" checked />
            <span> 立即发布 </span>
          </label>
          <label for="wait">
            <input type="radio" name="submitTime" class="wait" />
            <span> 定时发布 </span>
          </label>
        </div>
        <div class="btns">
          <div class="submit-btn" @click="submitNote()">发布</div>
          <div class="close-btn">取消</div>
        </div>
      </div>
    </div>
    <div class="box-right"></div>
  </div>
</template>

<style scoped lang="scss">
.main-box {
  background: white;
  width: 100%;
  max-width: 1180px;
  min-width: 1024px;
  min-height: 750px;
  margin: 16px auto 50px;
  border-radius: 8px;
  display: flex;
  .box-left {
    width: 73%;
    .left-title {
      display: flex;
      padding: 20px;
      align-items: center;
    }
    .edit-picture {
      padding-left: 30px;
      .picture-adds {
        display: flex;
        padding-top: 20px;
      }
    }
    .box-title {
      width: 700px;
      border: 1px solid #e4e6ec;
      margin-left: 30px;
      margin-top: 20px;
      border-radius: 5px;
      height: 30px;
      padding-left: 10px;
      outline: none;
      transition: border-color 0.3s ease;
    }
    .box-title:hover {
      border: 1px solid #c0c4cc;
      transition: border-color 0.3s ease;
    }
    .box-title:focus {
      border: 1px solid #ff2442;
      transition: border-color 0.3s ease;
    }
    .box-title::placeholder {
      color: #a8abb2;
    }
    .box-main {
      width: 700px;
      border: 1px solid #e4e6ec;
      margin-left: 30px;
      margin-top: 10px;
      border-radius: 5px;
      height: 100px;
      padding-left: 10px;
      outline: none;
      transition: border-color 0.3s ease;
      padding-top: 10px;
      font-family: BlackTi;
      resize: none;
    }
    .box-main::placeholder {
      color: #a8abb2;
      font-family: BlackTi;
    }
    .box-main:hover {
      border: 1px solid #c0c4cc;
      transition: border-color 0.3s ease;
    }
    .box-main:focus {
      border: 1px solid #ff2442;
      transition: border-color 0.3s ease;
    }

    .tags {
      display: flex;
      padding-left: 30px;
      padding-top: 10px;
      .tag {
        border: 1px solid #e4e6ec;
        border-radius: 5px;
        padding: 5px 10px;
        color: #606266;
        font-size: 14px;
        cursor: pointer;
        margin-right: 10px;
      }
    }
    .edit-submit {
      padding-left: 30px;
      padding-top: 20px;
      .submit-title {
        font-size: 20px;
      }
      .address {
        padding-top: 20px;
        .address-title {
          font-size: 14px;
        }
        .address-input {
          height: 30px;
          border: 1px solid #e4e6ec;
          margin-left: 20px;
          padding-left: 10px;
          border-radius: 5px;
          width: 450px;
          outline: none;
          transition: border-color 0.3s ease;
        }
        .address-input::placeholder {
          color: #a8abb2;
        }
        .address-input:hover {
          border: 1px solid #c0c4cc;
          transition: border-color 0.3s ease;
        }
        .address-input:focus {
          border: 1px solid #ff2442;
          transition: border-color 0.3s ease;
        }
      }
      .public-or-private {
        padding-top: 20px;
        display: flex;
        align-items: center;
        .title {
          font-size: 14px;
        }
        .public {
          margin-left: 25px;
          appearance: none;
          border-radius: 50%;
          width: 13px;
          height: 13px;
          border: 1px solid #e4e6ec;
          transition: 0.2s all linear;
          position: relative;
        }
        .public:checked {
          border: 5px solid red;
        }
        .private {
          margin-left: 25px;
          appearance: none;
          border-radius: 50%;
          width: 13px;
          height: 13px;
          border: 1px solid #e4e6ec;
          transition: 0.2s all linear;
          position: relative;
        }
        .private:checked {
          border: 5px solid red;
        }
        span {
          font-size: 14px;
        }
        input[type='radio']:checked ~ span {
          color: red;
        }
      }
      .submit-time {
        padding-top: 20px;
        display: flex;
        align-items: center;
        .title {
          font-size: 14px;
        }
        .now {
          margin-left: 25px;
          appearance: none;
          border-radius: 50%;
          width: 13px;
          height: 13px;
          border: 1px solid #e4e6ec;
          transition: 0.2s all linear;
          position: relative;
        }
        .now:checked {
          border: 5px solid red;
        }
        .wait {
          margin-left: 25px;
          appearance: none;
          border-radius: 50%;
          width: 13px;
          height: 13px;
          border: 1px solid #e4e6ec;
          transition: 0.2s all linear;
          position: relative;
        }
        .wait:checked {
          border: 5px solid red;
        }
        span {
          font-size: 14px;
        }
        input[type='radio']:checked ~ span {
          color: red;
        }
      }
      .btns {
        display: flex;
        padding-top: 20px;
        .submit-btn {
          background-color: #ff2442;
          padding: 7px 30px;
          color: white;
          font-size: 12px;
          border-radius: 3px;
          cursor: pointer;
        }
        .close-btn {
          background-color: #ffffff;
          padding: 7px 30px;
          font-size: 12px;
          border-radius: 3px;
          border: 1px solid #e4e6ec;
          margin-left: 10px;
          cursor: pointer;
        }
      }
    }
  }
  .box-right {
    width: 27%;
  }
}
</style>
<style>
.el-upload--picture-card:hover {
  border: 1px dashed #d9d9d9;
}
</style>
